﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BFlatCompile.Nodes
{
	public class StringConstant : Expression
	{
		private static readonly ValueTable table = new ValueTable();

		public static string[] GetStringTable()
		{
			return table.GetIds();
		}

		public static void SortTable()
		{
			table.SortByFrequency();
		}

		public string Value { get; private set; }

		public int Index { get { return table.GetId(this.Value); } }

		public Token Token { get; private set; }

		public StringConstant(string value, Token token)
		{
			value = UnescapeBackslashes(token, value);
			this.Value = value;
			table.Register(value);
			this.Token = token;
		}

		private static string UnescapeBackslashes(Token token, string value)
		{
			StringBuilder output = new StringBuilder();
			char c;
			for (int i = 0; i < value.Length; ++i)
			{
				c = value[i];
				if (c == '\\')
				{
					switch (value[++i])
					{
						case 'n': c = '\n'; break;
						case 't': c = '\t'; break;
						case 'r': c = '\r'; break;
						case '0': c = '\0'; break;
						case '\\': c = '\\'; break;
						default:
							throw new ParserException("Invalid string escape sequence: \\" + value[i], token);
					}
				}

				output.Append(c);
			}

			return output.ToString();
		}

		public override void ResolveCode(Class c, Dictionary<object, object> parents)
		{
			// nothing to resolve
		}

		public override void ResolveClassToThis(Class c)
		{
			// nothing to resolve
		}
	}
}
